package com.tsf.common.exception;

import com.tsf.common.result.R;
import com.tsf.common.result.REnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

@ControllerAdvice
@Slf4j
public class CommonExceptionHandler {


    /**
     * 此处错误可详分
     *
     * @param e
     * @return
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public R exceptionHandler(Exception e) {
        return R.error(new CommonErrorMessage(REnum.SERVICE_ERROR, String.format("%s", e.getMessage())));
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public R handleBindException(MethodArgumentNotValidException ex) {
        FieldError fieldError = ex.getBindingResult().getFieldError();
//        log.info("参数校验异常:{}({})", fieldError.getDefaultMessage(), fieldError.getField());
        return R.error(new CommonErrorMessage(REnum.PARAM_ERROR, String.format("%s(%s)", fieldError.getField(), fieldError.getDefaultMessage())));
    }

    @ExceptionHandler(BindException.class)
    @ResponseBody
    public R handleBindException(BindException ex) {
        //校验 除了 requestbody 注解方式的参数校验 对应的 bindingresult 为 BeanPropertyBindingResult
        FieldError fieldError = ex.getBindingResult().getFieldError();
//        log.info("必填校验异常:{}({})", fieldError.getDefaultMessage(), fieldError.getField());
        return R.error(new CommonErrorMessage(REnum.PARAM_ERROR, String.format("%s(%s)", fieldError.getField(), fieldError.getDefaultMessage())));
    }

}